﻿Public Class frmRGVAutoControl
    Private g_szInitFileName As String
    Public Sub New()
        ''加载DLL到exe的事件
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)
        InitializeComponent()
    End Sub

    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Private Sub frmRGVAutoControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then

        End If
        If Not HslControls.Authorization.SetAuthorizationCode("ce5ade06-6f14-4b0d-b9c2-0d625664dc3f") Then

        End If
        Dim d As String = My.Application.Info.Version.Major & "." & My.Application.Info.Version.Minor & "." & My.Application.Info.Version.Build
        Me.Text = Me.Text & "   (Ver." & d & ")"
        Me.g_szInitFileName = My.Application.Info.DirectoryPath & "\RGV.ini"

        '连接数据库
        connectDB()

        nudGJBnum.Value = getSysParam("YZZ_GJB_BOX_Num")
        NudGJBNeed.Value = getSysParam("GJB_need_Count_For_YZZ")
        nudFLBNeed.Value = getSysParam("FLB_need_Count_For_YZZ")

        '开始监控的画面动作
        tmServerMonitor.Interval = 500
        tmServerMonitor.Start()

    End Sub
    Public Sub connectDB()
        'イニシャルファイル情報取得

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        '得到当前用户名
        'g_LoginUser = GetIniFile("LOGIN", "user", "admin", g_szInitFileName)

        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

        setAllErrMsg()
    End Sub
    Private Sub tmServerMonitor_Tick(sender As Object, e As EventArgs) Handles tmServerMonitor.Tick
        Dim dtJBGWName As DataTable
        Dim dtCarName As DataTable

        Dim szSql As String = ""
        szSql = "select * from sf.b_record_jbgw_status_monitor order by sort "

        dtJBGWName = DBacs.ExecuteSql(szSql, -1)

        szSql = "select * from sf.b_record_rgv_status_monitor order by carname"

        dtCarName = DBacs.ExecuteSql(szSql, -1)
        '设置任务DataGridView
        setTaskDGV()
        '设置RGV的单车、双车模式
        Dim _rgvModel As String = getSysParam("RGV_model")
        If _rgvModel <> "" Then
            If _rgvModel = "1" Then
                lblRgvModel.Text = "单车模式"
            ElseIf _rgvModel = "2" Then
                lblRgvModel.Text = "双车模式"
            End If
        End If

        Dim _openStatus As String = "关"
        If getSysParam("RGV_AUTO_OPEN") = "0" Then
            _openStatus = "关"
        Else
            _openStatus = "开"
        End If

        lblAutoServiceStatus.Text = String.Format("自动控制服务：{0}", _openStatus)
        '判断计划
        Equals_GJB2_YZZ()

        If dtJBGWName.Rows.Count > 0 Then
            With dtJBGWName
                Dim _car1_Loc As String = ""
                Dim _car2_Loc As String = ""
                If dtCarName.Rows.Count > 0 Then
                    _car1_Loc = DBNULLtoZero(dtCarName.Rows(0)("CurrentLoc"))
                    _car2_Loc = DBNULLtoZero(dtCarName.Rows(1)("CurrentLoc"))
                End If

                gw1FKX.setStatus(.Rows(_1FKX_ROW), _car1_Loc, _car2_Loc)
                gw1FMS.setStatus(.Rows(_1FMS_ROW), _car1_Loc, _car2_Loc)

                gw1GMS1_1.setStatus(.Rows(_1GMS1_1_ROW), _car1_Loc, _car2_Loc)
                gw1GKX_1.setStatus(.Rows(_1GKX_1_ROW), _car1_Loc, _car2_Loc)
                gw1GMS1_2.setStatus(.Rows(_1GMS1_2_ROW), _car1_Loc, _car2_Loc)

                gw1GKX_3.setStatus(.Rows(_1GKX_3_ROW), _car1_Loc, _car2_Loc)
                gw1GMS_3.setStatus(.Rows(_1GMS_3_ROW), _car1_Loc, _car2_Loc)

                gw2FKS.setStatus(.Rows(_2FKS_ROW), _car1_Loc, _car2_Loc)
                gw2FMX.setStatus(.Rows(_2FMX_ROW), _car1_Loc, _car2_Loc)
                gw2GKS.setStatus(.Rows(_2GKS_ROW), _car1_Loc, _car2_Loc)
                gw2GMX.setStatus(.Rows(_2GMX_ROW), _car1_Loc, _car2_Loc)

                Rgv1.setStatus(dtCarName.Rows(0))
                Rgv2.setStatus(dtCarName.Rows(1))

                setAutoManualControl(1, .Rows(_1FKX_ROW)("controlmode"))
                setAutoManualControl(2, .Rows(_1GMS1_1_ROW)("controlmode"))
                setAutoManualControl(3, .Rows(_1GKX_3_ROW)("controlmode"))
                setAutoManualControl(4, .Rows(_2FKS_ROW)("controlmode"))
                setAutoManualControl(5, .Rows(_2GKS_ROW)("controlmode"))

            End With
        End If

    End Sub
    Private Function Equals_GJB2_YZZ() As Boolean
        Dim strSQL As String = ""

        strSQL &= " select b.gjb_material_code material_code  ,c.mst_value gjb_type"
        strSQL &= " from sf.b_workshop_current a inner join sf.t_prod_spec b "
        strSQL &= " On a.support_model=b.prod_spec_id "
        strSQL &= " inner join sf.t_mst_gjb c on c.material_code=b.gjb_material_code  "
        strSQL &= "where a.workshop=? and a.current_section=?"
        Dim dtGJBZP As DataTable = DBacs.ExecuteSql(strSQL, -1, g_cj_pt, g_ws_pt_gjbzp)

        If dtGJBZP.Rows.Count > 0 AndAlso DBNULLtoBlank(dtGJBZP.Rows(0)("material_code")) <> "" Then
        Else
            lblPlan.Text = "辊涂计划内容不全"
            Return False
        End If

        strSQL = ""
        strSQL &= " select b.gjb_material_code material_code ,c.mst_value gjb_type"
        strSQL &= " from sf.b_workshop_current a inner join sf.t_prod_spec b "
        strSQL &= " On a.support_model=b.prod_spec_id "
        strSQL &= " inner join sf.t_mst_gjb c on c.material_code=b.gjb_material_code  "
        strSQL &= " where  a.workshop=? "
        Dim dtYZZ As DataTable = DBacs.ExecuteSql(strSQL, -1, g_cj_yzz)
        If dtYZZ.Rows.Count > 0 AndAlso DBNULLtoBlank(dtYZZ.Rows(0)("material_code")) <> "" Then
        Else
            lblPlan.Text = "预组装计划内容不全"
            Return False
        End If

        If dtGJBZP.Rows(0)("material_code") = dtYZZ.Rows(0)("material_code") Then
            lblPlan.Text = String.Format("计划相同：一车间：{0}({1}) 二车间：{2}({3}) ", dtGJBZP.Rows(0)("gjb_type"), dtGJBZP.Rows(0)("material_code"), dtYZZ.Rows(0)("gjb_type"), dtYZZ.Rows(0)("material_code"))

            lblPlan.ForeColor = Color.DarkGreen
            Return True
        Else
            lblPlan.Text = String.Format("计划不同：一车间：{0}({1}) 二车间：{2}({3}) ", dtGJBZP.Rows(0)("gjb_type"), dtGJBZP.Rows(0)("material_code"), dtYZZ.Rows(0)("gjb_type"), dtYZZ.Rows(0)("material_code"))
            lblPlan.ForeColor = Color.Red
            Return False
        End If
    End Function
    Private Sub setTaskDGV()
        Dim dtTaskDetail As DataTable
        Dim szSql As String = ""
        szSql = "select a.taskno,a.memo,b.task_item_no,b.active,b.status ,b.car from sf.b_rgv_task a "
        szSql &= "inner join sf.b_rgv_task_detail b "
        szSql &= "on a.taskno=b.taskno "
        szSql &= "where a.status <> 100 "
        szSql &= " order by task_item_no asc"
        dtTaskDetail = DBacs.ExecuteSql(szSql, -1)

        'wait = 0  '等待
        'begin = 1 '开始
        'completed = 2 '单任务完成
        'remoteCarStop = 3 '远程RGV急停
        'carStop = 4 'RGV本地急停
        'remoteStationStop = 5 '接驳工位远程急停
        'stationStop = 6 '接驳工位本地急停
        'carDoorError = 7 '车门出错

        'WorkShop1DoorError = 8 '1车间门出错
        'WorkShop2DoorError = 9 '2车间门出错

        'carDNerror = 10 'RGV 下料错误
        'carUPerror = 11 'RGV 上料错误
        'stationDNerror = 12 '接驳工位 下料错误
        'stationUPerror = 13 '接驳工位 上料错误

        'carDNcompleted = 14      'RGV 下料完成
        'stationDNcompleted = 15  '接驳工位 下料完成
        'carUPcompleted = 16      'RGV 上料完成
        'stationUPcompleted = 17  '接驳工位 上料完成

        'carMoveError = 18        'RGV 移动出错
        'stationAllowError = 19   '接驳工位 允许上下料出错 

        ''carWaitTimeOut = 20      'RGV 动作超时
        ''stationWaitTimeOut = 21  '接驳工位 动作超时

        'otherError = 99          '其它错误
        'AllCompleted = 100       '全部任务完成

        dtTaskDetail.Columns.Add("activeName")
        dtTaskDetail.Columns.Add("statusName")

        If IsNothing(dtTaskDetail) = False AndAlso dtTaskDetail.Rows.Count > 0 Then
            lblTaskNo.Text = dtTaskDetail.Rows(0)("taskNo")
            lblMemo.Text = dtTaskDetail.Rows(0)("memo")
            If lblRgvModel.Text = "单车模式" Then
                lbltask_RGV.Text = "RGV" & dtTaskDetail.Rows(0)("car").ToString.Split(":")(1)
            End If

            For Each dr As DataRow In dtTaskDetail.Rows

                Dim act() As String = dr("active").ToString.Split(":")
                If act(0) = "TO" Then
                    act(0) = "▶"
                    act(1) = act(1).Replace("CDW", "充电位")
                Else
                    act(0) = ""
                    act(1) = act(1).Replace("GJB", "骨架板")
                    act(1) = act(1).Replace("FLB", "法兰板")
                    act(1) = act(1).Replace("DoorDN", "关车门")
                    act(1) = act(1).Replace("UP", "上料")
                    act(1) = act(1).Replace("DN", "下料")
                End If
                dr("activeName") = act(0) & act(1)


                Select Case dr("status")
                    Case 0
                        dr("statusName") = "等待"
                    Case 1
                        dr("statusName") = "开始"
                    Case 2
                        dr("statusName") = "完成"
                    Case 3
                        dr("statusName") = "RGV急停"
                    Case 4
                        dr("statusName") = "RGV急停"
                    Case 5
                        dr("statusName") = "工位急停"
                    Case 6
                        dr("statusName") = "工位急停"
                    Case 7
                        dr("statusName") = "车门坏"
                    Case 8
                        dr("statusName") = "1厂门坏"
                    Case 9
                        dr("statusName") = "2厂门坏"
                    Case 10
                        dr("statusName") = "RGV下错"
                    Case 11
                        dr("statusName") = "RGV上错"
                    Case 12
                        dr("statusName") = "下料错误"
                    Case 13
                        dr("statusName") = "上料错误"
                    Case 14
                        dr("statusName") = "RGV下完"
                    Case 15
                        dr("statusName") = "下料完成"
                    Case 16
                        dr("statusName") = "RGV上完"
                    Case 17
                        dr("statusName") = "上料完成"
                    Case 18
                        dr("statusName") = "移动出错"
                    Case 19
                        dr("statusName") = "不允许"
                    Case 99
                        dr("statusName") = "其它"
                End Select
            Next
            dgvTaskDetail.DataSource = dtTaskDetail
        Else
            lblTaskNo.Text = ""
            lblMemo.Text = ""
            lbltask_RGV.Text = ""
            dgvTaskDetail.DataSource = dtTaskDetail
        End If
    End Sub

    Private Sub setAutoManualControl(_Flg As Integer, _result As Boolean)
        Select Case _Flg
            Case 1
                If _result = False Then
                    lblAM_1F.Text = "手动"
                    lblAM_1F.ForeColor = Color.White
                    lblAM_1F.BackColor = Color.Red
                Else
                    lblAM_1F.Text = "自动"
                    lblAM_1F.ForeColor = Color.Black
                    lblAM_1F.BackColor = Color.LawnGreen
                End If

            Case 2
                If _result = False Then
                    lblAM_1G2.Text = "手动"

                    lblAM_1G2.ForeColor = Color.White
                    lblAM_1G2.BackColor = Color.Red
                Else
                    lblAM_1G2.Text = "自动"
                    lblAM_1G2.ForeColor = Color.Black
                    lblAM_1G2.BackColor = Color.LawnGreen
                End If
            Case 3
                If _result = False Then
                    lblAM_1G3.Text = "手动"
                    lblAM_1G3.ForeColor = Color.White
                    lblAM_1G3.BackColor = Color.Red
                Else
                    lblAM_1G3.Text = "自动"
                    lblAM_1G3.ForeColor = Color.Black
                    lblAM_1G3.BackColor = Color.LawnGreen
                End If
            Case 4

                If _result = False Then
                    lblAM_2F.Text = "手动"
                    lblAM_2F.ForeColor = Color.White
                    lblAM_2F.BackColor = Color.Red
                Else
                    lblAM_2F.Text = "自动"
                    lblAM_2F.ForeColor = Color.Black
                    lblAM_2F.BackColor = Color.LawnGreen
                End If
            Case 5
                If _result = False Then
                    lblAM_2G.Text = "手动"
                    lblAM_2G.ForeColor = Color.White
                    lblAM_2G.BackColor = Color.Red
                Else
                    lblAM_2G.Text = "自动"
                    lblAM_2G.ForeColor = Color.Black
                    lblAM_2G.BackColor = Color.LawnGreen
                End If

        End Select
    End Sub

    Private Sub btnGJBNumOnLine_Click(sender As Object, e As EventArgs) Handles btnGJBNumOnLine.Click

        setSysParam("YZZ_GJB_BOX_Num", nudGJBnum.Value)
        setSysParam("FLB_need_Count_For_YZZ", nudFLBNeed.Value)
        setSysParam("GJB_need_Count_For_YZZ", NudGJBNeed.Value)

    End Sub
    Private WithEvents tmServerMonitor As New Windows.Forms.Timer
    Const _1FKX_ROW As Integer = 0
    Const _1FMS_ROW As Integer = 1
    Const _1GMS1_1_ROW As Integer = 2
    Const _1GKX_1_ROW As Integer = 3
    Const _1GMS1_2_ROW As Integer = 4
    Const _1GMS_3_ROW As Integer = 5
    Const _1GKX_3_ROW As Integer = 6
    Const _2FKS_ROW As Integer = 7
    Const _2FMX_ROW As Integer = 8
    Const _2GMX_ROW As Integer = 9
    Const _2GKS_ROW As Integer = 10

    Private Sub btnClearTask_Click(sender As Object, e As EventArgs) Handles btnClearTask.Click

        If lblTaskNo.Text = "" Then Exit Sub

        If getSysParam("RGV_AUTO_TASK_PASUE") Then
            MsgBox("请先暂停任务。")
            Exit Sub
        End If
        If MsgBox("确定要删除任务吗？", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            If clearTask() <> 1 Then
                MsgBox("删除失败")
            End If
        End If
    End Sub
    Private Function clearTask() As Integer

        Dim szSql As String = ""
        DBacs.BeginTransaction()
        Try
            szSql = " delete from sf.b_rgv_task_detail where taskno=? "
            DBacs.ExecuteUpdateSql(szSql, -1, lblTaskNo.Text)

            szSql = " delete from sf.b_rgv_task where taskno=? "
            DBacs.ExecuteUpdateSql(szSql, -1, lblTaskNo.Text)
            DBacs.CommitTransaction()
            Return 1
        Catch ex As Exception
            DBacs.RollbackTransaction()
            Return 2
        End Try

    End Function

    Private Sub btnOpenAutoService_Click(sender As Object, e As EventArgs) Handles btnOpenAutoService.Click
        If btnOpenAutoService.Text = "启动自动控制" Then
            btnOpenAutoService.Text = "关闭自动控制"
            setSysParam("RGV_AUTO_OPEN", "0")
        Else
            btnOpenAutoService.Text = "启动自动控制"
            setSysParam("RGV_AUTO_OPEN", "1")
        End If
    End Sub

    Private Sub btnPauseTask_Click(sender As Object, e As EventArgs) Handles btnPauseTask.Click
        If btnPauseTask.Text = "暂停任务" Then
            btnPauseTask.Text = "重启任务"
            setSysParam("RGV_AUTO_TASK_PASUE", "1")
        Else
            btnPauseTask.Text = "暂停任务"
            setSysParam("RGV_AUTO_TASK_PASUE", "0")
        End If
    End Sub
End Class